import {resetPasswordUsingPost, userLogoutUsingPost} from '@/services/backend/userController';
import {LogoutOutlined, SafetyOutlined, UserOutlined} from '@ant-design/icons';
import { ModalForm, ProFormText } from '@ant-design/pro-components';
import { history, useModel } from '@umijs/max';
import {Avatar, Button, Space, message} from 'antd';
import { stringify } from 'querystring';
import type { MenuInfo } from 'rc-menu/lib/interface';
import React, {useCallback, useState} from 'react';
import { flushSync } from 'react-dom';
import { Link } from 'umi';
import HeaderDropdown from '../HeaderDropdown';

export type GlobalHeaderRightProps = {
  menu?: boolean;
};

export const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({  }) => {
  /**
   * 退出登录，并且将当前的 url 保存
   */
  const loginOut = async () => {
    await userLogoutUsingPost();
    const { search, pathname } = window.location;
    const urlParams = new URL(window.location.href).searchParams;
    /** 此方法会跳转到 redirect 参数所在的位置 */
    const redirect = urlParams.get('redirect');
    // Note: There may be security issues, please note
    if (window.location.pathname !== '/user/login' && !redirect) {
      history.replace({
        pathname: '/user/login',
        search: stringify({
          redirect: pathname + search,
        }),
      });
    }
  };

  const { initialState, setInitialState } = useModel('@@initialState');
  const [modalVisit, setModalVisit] = useState(false);


  const onMenuClick = useCallback(
    (event: MenuInfo) => {
      const { key } = event;
      if (key === 'logout') {
        flushSync(() => {
          setInitialState((s) => ({ ...s, currentUser: undefined }));
        });
        loginOut();
        return;
      }
      if (key === 'resetPassword'){
        flushSync(() => {
          setModalVisit(true)
        });
      }
    },
    [setInitialState],
  );

  const { currentUser } = initialState || {};

  if (!currentUser) {
    return (
      <Link to="/user/login">
        <Button type="primary" shape="round">
          登录
        </Button>
      </Link>
    );
  }

  const menuItems = [
    {
      key: 'resetPassword',
      icon: <SafetyOutlined />,
      label: '重置密码',
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
    },
  ];

  return (
    <>
      <HeaderDropdown
        menu={{
          selectedKeys: [],
          onClick: onMenuClick,
          items: menuItems,
        }}
      >
        <Space>
          <Avatar size="small" icon={<UserOutlined />} />
          <span className="anticon">{currentUser?.userName ?? '无名'}</span>
        </Space>
      </HeaderDropdown>
      <ModalForm
        title="修改密码"
        open={modalVisit}
        width={500}
        onFinish={async (value) => {
          const { data } = await resetPasswordUsingPost(value)
          if (data) {
            await loginOut()
            message.warning('密码修改成功！请重新登录');
            return true;
          }else {
            message.error('修改失败');
          }
          return false;
        }}
        onOpenChange={setModalVisit}
      >
        <ProFormText.Password
          name="userPassword"
          label="新密码"
          placeholder="请输入新的密码"
          rules={[
            {
              required: true,
              message: '请输入密码',
            },
            {
              min: 8,
              message: '密码至少8位',
            },
          ]}
        />
        <ProFormText.Password
          name="checkPassword"
          label="重复密码"
          placeholder="请重复密码"
          rules={[
            {
              required: true,
              message: '请输入密码',
            },
            {
              min: 8,
              message: '密码至少8位',
            },
          ]}
        />
      </ModalForm>
    </>
  );
};

export const AvatarName = () => {};
